//
//  ImmediateEvaluationViewController.m
//  NewCommunity
//
//  Created by Aaron on 2017/10/16.
//  Copyright © 2017年 ZP. All rights reserved.
//

#import "ImmediateEvaluationViewController.h"
#import "ImmediateEvaluationTableViewCell.h"
#import "TZImagePickerController.h"
#import "UIPlaceHolderTextView.h"
#import "ImmediateEvaluationCollectionViewCell.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

@interface ImmediateEvaluationViewController ()<UITableViewDelegate, UITableViewDataSource, TZImagePickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, MJPhotoBrowserDelegate, ImmediateEvaluationTableViewCellDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIPlaceHolderTextView * textView;
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)UIView * headerView;

@property (nonatomic, strong)UIAlertController * alertController;
@property (nonatomic, strong)TZImagePickerController * imagePicker;
@property (nonatomic, strong)UIImagePickerController * imagePickerController;
@property (nonatomic,strong)NSMutableDictionary *objdic;

@property (nonatomic, strong)NSMutableArray * imageArray;

@property (nonatomic,assign) NSInteger aaa;
@end


//商品立即评价请求接口
@implementation ImmediateEvaluationViewController (NetWorking)
- (void)userEvaluationgoods
{
    NSDictionary * dic = @{
                           @"level":@(self.aaa),
                           @"content":self.textView.text,
                           @"tid":@(self.travelID),
                           @"mid":[UserModel intance].member_id,
                           @"token":[UserModel intance].token
                           };
    WS(ws)
    [[HUDHelper sharedInstance]syncLoading:@"翻箱中..."];
    [[HttpRequest shardWebUtil]postNetworkRequestURLString:Url(@"/index/toEvaluate") andParas:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [self.imageArray removeObjectAtIndex:self.imageArray.count-1];
        for (UIImage *image in self.imageArray) {
            NSData *data = UIImageJPEGRepresentation(image, .1);
            NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
            [formData appendPartWithFileData:data name:@"pic[]" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
        }
    } andTransferGottenData:^(id obj, NSError *error) {
        [[HUDHelper sharedInstance]syncStopLoading];
        if (error)
        {
            [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
        }
        else
        {
            if ([obj[@"code"] integerValue] == 100000) {
                
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
                [ws.navigationController popViewControllerAnimated:YES];
                
            }else{
                [[HUDHelper sharedInstance]tipMessage:obj[@"msg"]];
            }
        }
    }];
}
@end

@implementation ImmediateEvaluationViewController

-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"fankui"]]];
    }
    return _imageArray;
}

-(UIImagePickerController *)imagePickerController
{
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

-(UIAlertController *)alertController
{
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从图库选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _imagePicker = [[TZImagePickerController alloc]initWithMaxImagesCount:4 - self.imageArray.count delegate:self];
            _imagePicker.allowPickingVideo = NO;
            
            _imagePicker.allowTakePicture = NO;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *addPhoneAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
            {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePickerController animated:YES completion:nil];
            }
            else
            {
                //  [self showMessage:@"当前设备无摄像头，请从相册获取"];
            }
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [photoAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [addPhoneAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [cancelAction setValue:getColor(@"584f60@") forKey:@"_titleTextColor"];
        [_alertController addAction:photoAction];
        [_alertController addAction:addPhoneAction];
        [_alertController addAction:cancelAction];
        
    }
    return _alertController;
}
-(void)initViews
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [UIView new];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    _headerView = [[UIView alloc]init];
    _headerView.backgroundColor = [UIColor whiteColor];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 12)];
    lineView.backgroundColor = getColor(@"f2f2f2");
    [_headerView addSubview:lineView];
    
    _textView = [[UIPlaceHolderTextView alloc]initWithFrame:CGRectMake(15, 12, SCREEN_WIDTH - 30, 93)];
    _textView.backgroundColor = [UIColor whiteColor];
    self.textView.placeholder = @"请输入您要评论的内容";
    [_headerView addSubview:_textView];
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 45) / 4, (SCREEN_WIDTH - 45) / 4);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 0.1;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_textView.frame) + 5, SCREEN_WIDTH, (SCREEN_WIDTH - 45) / 4) collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:_collectionView];
    
    [_collectionView registerClass:[ImmediateEvaluationCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([ImmediateEvaluationCollectionViewCell class])];
    
    _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, CGRectGetMaxY(_collectionView.frame) + 10);
    _tableView.tableHeaderView = _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _aaa=5;
    [self initViews];
    self.navigationItem.title = @"立即评价";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ImmediateEvaluationTableViewCell * cell = [ImmediateEvaluationTableViewCell cellForTableView:tableView];
    cell.delegate = self;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 222;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    
    UIButton * submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitButton setTitle:@"提交" forState:UIControlStateNormal];
    submitButton.backgroundColor = getColor(@"ffbb02");
    submitButton.layer.cornerRadius = 8;
    submitButton.titleLabel.font = DEF_FontSize_14;
    submitButton.layer.masksToBounds = YES;
     [submitButton addTarget:self action:@selector(submitButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:submitButton];
    
    submitButton.frame = CGRectMake(15, 172, SCREEN_WIDTH - 30, 40);
    
    return view;
}

#pragma mark - ImmediateEvaluationTableViewCellDelegate
//星星评分
-(void)scoreWithDescribe:(NSInteger)describe logistics:(NSInteger)logistics attitude:(NSInteger)attitude
{
    _aaa=describe;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.imageArray.count < 4) {
        return self.imageArray.count;
    }
    return self.imageArray.count - 1;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImmediateEvaluationCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ImmediateEvaluationCollectionViewCell class]) forIndexPath:indexPath];
    cell.imageView.image = self.imageArray[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.imageArray.count < 4) {
        if (indexPath.row == self.imageArray.count - 1) {
            [self presentViewController:self.alertController animated:YES completion:nil];
            return;
        }
    }
    //1.创建图片浏览器
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    //2.告诉图片浏览器显示所有的图片
    NSMutableArray *photos = [NSMutableArray array];
    for (int i = 0 ; i < self.imageArray.count - 1; i++) {
        //传递数据给浏览器
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        mjPhoto.image = self.imageArray[i];
        ImmediateEvaluationCollectionViewCell *cell = (ImmediateEvaluationCollectionViewCell*)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        mjPhoto.srcImageView = cell.imageView; //设置来源哪一个UIImageView
        [photos addObject:mjPhoto];
    }
    brower.photos = photos;
    brower.isShowDeleteButton = YES;
    brower.delegate = self;
    //3.设置默认显示的图片索引
    brower.currentPhotoIndex = indexPath.row;
    //4.显示浏览器
    [brower show];
}

#pragma mark - MJPhotoBrowserDelegate

-(void)photoBrowser:(MJPhotoBrowser *)photoBrowser didDeletePhotoAtIndex:(NSInteger)index
{
    if (index < self.imageArray.count) {
        UIImage *image = self.imageArray[index];
        [self.imageArray removeObject:image];
        [self.collectionView reloadData];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (self.imageArray.count >=4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.imageArray insertObject:image atIndex:self.imageArray.count - 1];
    [_collectionView reloadData];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos
{
    if (self.imageArray.count + photos.count > 4) {
        [[HUDHelper sharedInstance] tipMessage:@"您最多选择3张照片"];
        return;
    }
    [self.imageArray removeObjectAtIndex:self.imageArray.count - 1];
    [self.imageArray addObjectsFromArray:photos];
    [self.imageArray addObject:[UIImage imageNamed:@"fankui"]];
    
    [_collectionView reloadData];
}

//提交按钮事件
-(void)submitButtonAction
{
    [self userEvaluationgoods];
    [self.navigationController popViewControllerAnimated:YES];
    
}
@end
